from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import os
import pymysql
from datetime import datetime
from decimal import Decimal

# 创建Flask应用实例
app = Flask(__name__)
CORS(app)  # 启用跨域资源共享

# 配置
app.config['JSON_AS_ASCII'] = False  # 确保中文正常显示

# 数据库配置
DB_CONFIG = {
    'host': '121.4.254.125',
    'port': 3306,
    'user': 'huawei_ending',
    'password': '123456',  # 请修改为您的数据库密码
    'db': 'huawei_ending',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

# 商品数据存储路径
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
GOODS_FILE = os.path.join(DATA_DIR, 'goods.json')
ORDERS_FILE = os.path.join(DATA_DIR, 'orders.json')

# 确保数据目录存在
os.makedirs(DATA_DIR, exist_ok=True)

# 数据库连接函数
def get_db_connection():
    return pymysql.connect(**DB_CONFIG)

# 初始化数据文件
def init_data_files():
    # 初始化商品数据
    if not os.path.exists(GOODS_FILE):
        with open(GOODS_FILE, 'w', encoding='utf-8') as f:
            json.dump({
                "categories": [
                    {
                        "id": "1",
                        "name": "人气TOP",
                        "goods": [
                            {
                                "id": "101",
                                "title": "芝芝莓莓",
                                "photo": "https://img.alicdn.com/imgextra/i3/2200724907121/O1CN01OQwJ6S22CdkHCdZ3u_!!2200724907121.jpg",
                                "txt": "选用当季草莓搭配清爽茉莉花茶",
                                "price": 19.0,
                                "sizes": ["中杯", "大杯"],
                                "temperatures": ["冰", "少冰", "去冰", "常温", "热"],
                                "sweetness": ["不加糖", "微糖", "半糖", "少糖", "正常糖"]
                            }
                        ]
                    }
                ]
            }, f, ensure_ascii=False, indent=2)
    
    # 初始化订单数据
    if not os.path.exists(ORDERS_FILE):
        with open(ORDERS_FILE, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False, indent=2)

# 获取所有商品分类
@app.route('/api/categories', methods=['GET'])
def get_categories():
    try:
        with open(GOODS_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
            return jsonify({
                "code": 0,
                "message": "获取分类成功",
                "data": data["categories"]
            })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取分类失败: {str(e)}",
            "data": None
        }), 200

# 获取特定分类的商品
@app.route('/api/goods/<category_id>', methods=['GET'])
def get_goods_by_category(category_id):
    try:
        with open(GOODS_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
            for category in data["categories"]:
                if category["id"] == category_id:
                    return jsonify({
                        "code": 0,
                        "message": "获取商品成功",
                        "data": category["goods"]
                    })
            
            return jsonify({
                "code": 404,
                "message": "分类不存在",
                "data": None
            }), 404
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取商品失败: {str(e)}",
            "data": None
        }), 500

# 获取所有商品
@app.route('/api/goods', methods=['GET'])
def get_all_goods():
    try:
        with open(GOODS_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
            all_goods = []
            for category in data["categories"]:
                all_goods.extend(category["goods"])
            
            return jsonify({
                "code": 0,
                "message": "获取所有商品成功",
                "data": all_goods
            })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取所有商品失败: {str(e)}",
            "data": None
        }), 500

# 用户注册
@app.route('/api/user/register', methods=['POST'])
def register_user():
    try:
        user_data = request.json
        
        # 验证用户数据
        if not user_data or "username" not in user_data or "password" not in user_data:
            return jsonify({
                "code": 400,
                "message": "用户数据不完整",
                "data": None
            }), 400
        
        username = user_data.get('username')
        password = user_data.get('password')
        nickname = user_data.get('nickname', username)
        phone = user_data.get('phone', '')
        # 连接数据库
        conn = get_db_connection()
        try:
            with conn.cursor() as cursor:
                # 检查用户名是否已存在
                cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
                if cursor.fetchone():
                    return jsonify({
                        "code": 409,
                        "message": "用户名已存在",
                        "data": None
                    }), 200
                
                # 检查手机号是否已存在
                if phone:
                    cursor.execute("SELECT * FROM users WHERE phone = %s", (phone,))
                    if cursor.fetchone():
                        return jsonify({
                            "code": 409,
                            "message": "手机号已被注册",
                            "data": None
                        }), 200
                
                # 插入新用户
                cursor.execute(
                    "INSERT INTO users (username, password , phone, nickname, created_at) VALUES (%s, %s,%s, %s, %s)",
                    (username, password, phone, nickname, datetime.now())
                )
                conn.commit()
                
                return jsonify({
                    "code": 0,
                    "message": "注册成功",
                    "data": {"username": username}
                })
        finally:
            conn.close()
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"注册失败: {str(e)}",
            "data": None
        }), 200

# 用户登录
@app.route('/api/user/login', methods=['POST'])
def login_user():
    try:
        login_data = request.json
        
        # 验证登录数据
        if not login_data or "username" not in login_data or "password" not in login_data:
            return jsonify({
                "code": 400,
                "message": "登录数据不完整",
                "data": None
            }), 400
        
        username = login_data.get('username')
        print(username)
        password = login_data.get('password')
        print(password)
        # 连接数据库
        conn = get_db_connection()
        try:
            with conn.cursor() as cursor:
                # 检查用户名和密码
                cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
                user = cursor.fetchone()
                
                if user:
                    # 更新最后登录时间
                    cursor.execute("UPDATE users SET last_login = %s WHERE id = %s", (datetime.now(), user['id']))
                    conn.commit()
                    print("登录成功！")
                    return jsonify({
                        "code": 0,
                        "message": "登录成功",
                        "data": {
                            "username": user['username'],
                            "nickname": user['nickname']
                        }
                    })
                else:
                    return jsonify({
                        "code": 401,
                        "message": "用户名或密码错误",
                        "data": None
                    }), 200
        finally:
            conn.close()
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"登录失败: {str(e)}",
            "data": None
        }), 200

# 提交订单
@app.route('/api/orders', methods=['POST'])
def create_order():
    try:
        order_data = request.json
        
        # 验证订单数据
        if not order_data or "items" not in order_data or not order_data["items"] or "username" not in order_data:
            return jsonify({
                "code": 400,
                "message": "订单数据不完整",
                "data": None
            }), 400
        
        username = order_data.get('username')
        shop = order_data.get('shop', '广东外语外贸大学南国商学院')
        total_price = order_data.get('totalPrice', 0)
        items = order_data.get('items', [])
        print(items)
        # 连接数据库
        conn = get_db_connection()
        try:
            with conn.cursor() as cursor:
                # 创建订单
                cursor.execute(
                    "INSERT INTO orders (username, shopName, totalPrice, status, createTime) VALUES (%s, %s, %s, %s, %s)",
                    (username, shop, total_price, "待付款", datetime.now())
                )
                order_id = cursor.lastrowid
                
                # 添加订单项
                for item in items:
                    cursor.execute(
                        """INSERT INTO order_items 
                        (order_id, title, photo, price, count, userid, size, temperature, sweetness) 
                        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
                        (
                            order_id, 
                            item.get('title', ''), 
                            item.get('photo', ''),
                            item.get('price', 0),
                            item.get('count', 1),
                            item.get('userid', username),
                            item.get('size', '默认规格'),
                            item.get('temperature', '冰'),
                            item.get('sweetness', '正常糖')
                        )
                    )
                
                conn.commit()
                
                return jsonify({
                    "code": 0,
                    "message": "订单创建成功",
                    "data": {"order_id": order_id}
                })
        finally:
            conn.close()
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"创建订单失败: {str(e)}",
            "data": None
        }), 200

# 获取用户订单
@app.route('/api/orders/<username>', methods=['GET'])
def get_user_orders(username):
    try:
        conn = get_db_connection()
        try:
            with conn.cursor() as cursor:
                # 首先获取用户的所有订单
                cursor.execute("""
                    SELECT id, shopName, totalPrice, status, createTime
                    FROM orders
                    WHERE username = %s
                    ORDER BY createTime DESC
                """, (username,))
                
                orders = cursor.fetchall()
                
                result = []
                
                # 对于每个订单，获取其订单项
                for order in orders:
                    # 处理订单数据类型
                    order_id = order['id']
                    
                    # 转换状态为前端枚举值
                    status_map = {
                        "待付款": "unpaid",
                        "待制作": "pending",
                        "制作中": "processing",
                        "已完成": "completed",
                        "已取消": "canceled"
                    }
                    
                    order['status'] = status_map.get(order['status'], "pending")
                    
                    # 处理Decimal类型
                    if 'totalPrice' in order and isinstance(order['totalPrice'], (Decimal)):
                        order['totalPrice'] = float(order['totalPrice'])
                    
                    # 转换日期时间为字符串
                    if 'createTime' in order and order['createTime']:
                        order['createTime'] = order['createTime'].strftime('%Y-%m-%d %H:%M:%S')
                    
                    # 获取该订单的所有订单项
                    cursor.execute("""
                        SELECT id, title, photo, price, count, userid, size, temperature, sweetness
                        FROM order_items
                        WHERE order_id = %s
                    """, (order_id,))
                    
                    items = cursor.fetchall()
                    
                    # 处理订单项数据类型
                    for item in items:
                        # 处理Decimal类型
                        if 'price' in item and isinstance(item['price'], (Decimal)):
                            item['price'] = float(item['price'])
                        if 'count' in item:
                            item['count'] = int(item['count'])
                        
                        # 确保id是字符串类型
                        if 'id' in item:
                            item['id'] = str(item['id'])
                    
                    # 将订单项添加到订单中
                    order['items'] = items
                    
                    # 将订单添加到结果列表
                    result.append(order)
                
                return jsonify({
                    "code": 0,
                    "message": "获取订单成功",
                    "data": result
                })
        finally:
            conn.close()
    except Exception as e:
        print(f"获取订单失败: {str(e)}")
        return jsonify({
            "code": 500,
            "message": f"获取订单失败: {str(e)}",
            "data": None
        }), 200

# 使用with_app_context替代before_first_request
@app.route('/api/init', methods=['GET'])
def initialize_app():
    init_data_files()
    return jsonify({
        "code": 0,
        "message": "应用初始化成功",
        "data": None
    })

# 修改密码接口
@app.route('/api/user/reset-password', methods=['POST'])
def reset_password():
    try:
        data = request.json
        
        # 验证请求数据
        if not data or "username" not in data or "phone" not in data or "password" not in data:
            return jsonify({
                "code": 400,
                "message": "请求数据不完整",
                "data": None
            }), 200
        
        username = data.get('username')
        phone = data.get('phone')
        new_password = data.get('password')
        print(username,phone,new_password)
        # 连接数据库
        conn = get_db_connection()
        try:
            with conn.cursor() as cursor:
                # 查询用户是否存在且手机号匹配
                cursor.execute("SELECT * FROM users WHERE username = %s AND phone = %s", (username, phone))
                user = cursor.fetchone()
                
                if not user:
                    return jsonify({
                        "code": 404,
                        "message": "用户名或手机号不匹配",
                        "data": None
                    }), 200
                
                # 更新密码
                cursor.execute("UPDATE users SET password = %s WHERE id = %s", (new_password, user['id']))
                conn.commit()
                
                return jsonify({
                    "code": 0,
                    "message": "密码修改成功",
                    "data": None
                })
        finally:
            conn.close()
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"修改密码失败: {str(e)}",
            "data": None
        }), 200

# 主函数
if __name__ == '__main__':
    # 确保数据文件存在
    init_data_files()
    # 启动应用
    app.run(host='0.0.0.0', port=5000, debug=True) 